package com.example.order.config.feign;

import com.example.order.entity.StockDTO;
import com.example.order.feign.StockClientFeign;
import feign.FeignException;
import feign.Request;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;

/**
 * @Author: 唐佳辉
 * @CreateTime： 2025-05-08-11:23
 * @Description: 降级处理 自定义返回  此处也许可以使用统一异常处理 去处理这个降级处理 此处可以是做更加精细的粒度处理 若想使用自定义返回需要添加sentinal依赖 以及在配置文件添加sentinal 开启配置
 * @Version：1.0
 */
@Component
@Slf4j
public class StockServiceFallbackFactory implements FallbackFactory<StockClientFeign> {
    @Override
    public StockClientFeign create(Throwable cause) {

        log.info("StockServiceFallbackFactory create");
        return new StockClientFeign() {
            @Override
            public String stock() {
                if (cause instanceof FeignException) {
                    FeignException feignException = (FeignException) cause;
                    if (feignException.status() == 500) {
                        return "Service error occurred. Please try again later.";
                    } else if (feignException.status() == 503) {
                        return "Service is temporarily unavailable.";
                    }
                }
                return "Fallback response: Unable to get weather data.";
            }

            @Override
            public String getStockDTO(StockDTO stockDTO) {
                if (cause instanceof FeignException) {
                    FeignException feignException = (FeignException) cause;
                    if (feignException.status() == 500) {
                        return "Service error occurred. Please try again later.";
                    } else if (feignException.status() == 503) {
                        return "Service is temporarily unavailable.";
                    }
                }
                return "Fallback response: Unable to get weather data.";
            }

            @Override
            public String getInfo(Request.Options options, Long id) {
                return "";
            }
        };

    }
}
